package org.linuxsogood.boot.chat;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.Executors;

/**
 * @author honway.liu
 * @date 2019/12/1 10:00 下午
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
@Slf4j
public class NioChatClient {

    private Selector selector;

    private SocketChannel socketChannel;

    public NioChatClient() throws IOException {
        socketChannel = SocketChannel.open(new InetSocketAddress(6666));
        socketChannel.configureBlocking(false);

        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void start() throws IOException {
        while (true) {
            int readyCount = selector.select(1000);
            while (readyCount > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    if (selectionKey.isAcceptable()) {
                        log.info("connected to server: {}", channel.getRemoteAddress());

                        channel.configureBlocking(false);
                        channel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        log.info("receive data from server: {}", channel.getRemoteAddress());
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        log.info("message is : [{}]", new String(buffer.array()));
                    }
                    iterator.remove();
                }
            }
        }
    }

    public void sendMsg(String msg) throws IOException {
        socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
    }

    public static void main(String[] args) throws IOException {
        NioChatClient nioChatClient = new NioChatClient();
        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                nioChatClient.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.nextLine();
            nioChatClient.sendMsg(msg);
        }
    }
}
